<template>
  <a-modal
    :open="visible"
    :title="'验证邮箱'"
    @cancel="handleCancel"
    :footer="null"
    :maskClosable="false"
  >
    <div>
      <div class="input-group">
        <a-input
          style="margin-bottom: 20px; width: 100%"
          v-model:value="props.email"
          type="email"
          disabled
          placeholder="Enter your email"
        />
      </div>
      <div class="input-group code-group">
        <div class="code-input">
          <a-input
            v-model:value="formData.code"
            placeholder="Enter verification code"
          >
            <template #addonAfter>
              <a-button
                :disabled="isCounting"
                @click="sendVerificationCode(props.email)"
                type="primary"
                :class="{ disabled: isCounting }"
              >
                {{ countdown > 0 ? `${countdown}s` : "Send Code" }}
              </a-button>
            </template>
          </a-input>
        </div>
        <div v-if="isReg" class="error-message">
          Email has been registered!
        </div>
      </div>
      <a-button type="primary" class="submit-btn" @click="handleSubmit">Submit</a-button>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { postSendEmailCode, postVerifyEmail } from "@/api/index";
import { useUserStore } from "@/store/user";
import { message } from "ant-design-vue";
import { ref, reactive, defineProps, defineEmits } from "vue";

const userStore = useUserStore();
const userInfo = ref<any>(null);

const props = defineProps({
  email: {
    type: String,
    required: true,
    default: ""
  },
  visible: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(["dialogVisible", "update:visible", "success"]);

const formData = reactive({
  email: "",
  code: "",
});

// 倒计时相关
const countdown = ref(0);
const isCounting = ref(false);
let timer: NodeJS.Timeout | null = null;
const isReg = ref(false);

// 发送验证码
const sendVerificationCode = async (val: string) => {
  if (!val) {
    message.warning("Please enter email.");
    return;
  }
  // 开始倒计时
  isCounting.value = true;
  countdown.value = 60;
  timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      if (timer) clearInterval(timer);
      isCounting.value = false;
    }
  }, 1000);
  await postSendEmailCode({ email: val }).then((res: any) => {
    if (res.code === 200) {
      message.success("发送成功");
      return;
    }else if (res.code === 40003) {
      message.error('Email has been registered!');
      isReg.value = true
      setTimeout(() => {
        isReg.value = false
      }, 4000);
      return;
    } else {
      message.error(`${res.msg}`);
      return;
    }
  });
};

// 处理提交
const handleSubmit = async () => {
  formData.email = props.email;
  if (!formData.code) {
    message.warning("Please fill all fields.");
    return;
  }

  // 这里添加实际提交逻辑
  await postVerifyEmail(formData).then((res: any) => {
    if (res.code === 200) {
      message.success(`${res.msg + 'Enjoy discounts and get coupons for merchandise!'}`);
      //更新用户信息
      userStore.setUserInfo();
      // 关闭对话框
      emit("dialogVisible", false);
      emit("update:visible", false);
      emit("success", true);
    } else {
      const msg = res.msg;
      message.error(msg);
    }
  });
};

// 处理取消
const handleCancel = () => {
  emit("update:visible", false);
  emit("dialogVisible", false);
};
</script>

<style scoped lang="scss">
.input-group {
  margin-bottom: 16px;
}

.code-input {
  display: flex;
  gap: 10px;
}

:deep(.ant-input-group-addon) {
  padding: 0;
}

:where(.css-dev-only-do-not-override-12unj27).ant-btn-primary {
  box-shadow:none;
}

:where(.css-dev-only-do-not-override-12unj27).ant-input-group .ant-input-group-addon {
  border: none;
}

:deep(.ant-btn.disabled) {
  background-color: #999;
  color: white;
  border-color: #999;
  cursor: not-allowed;
}

.submit-btn {
  width: 100%;
  margin-top: 20px;
  height: 40px;
  font-size: 16px;
}

.error-message {
  color: red;
  margin-top: 10px;
  font-size: 0.75rem;
}
</style>
